package com.example.cmh.controller;

import com.example.cmh.common.Result;
import com.example.cmh.common.UploadUtil;
import com.example.cmh.pojo.Department;
import com.example.cmh.pojo.Tenant;
import com.example.cmh.pojo.User;
import com.example.cmh.service.DepartmentService;
import com.example.cmh.service.TenantService;
import com.example.cmh.service.UserService;
import com.example.cmh.common.CaptchaUtil;
import com.example.cmh.pojo.RegisterDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.HashMap;

/**
 * 租户控制器
 */
@RestController
@RequestMapping("/api/tenant")
@CrossOrigin
@Slf4j
public class TenantController {
    
    @Autowired
    private TenantService tenantService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private DepartmentService departmentService;
    
    // 本地验证码缓存，key为uuid，value为验证码字符串
    private static final Map<String, String> captchaCache = new ConcurrentHashMap<>();
    
    /**
     * 分页条件搜索租户信息
     * @param page 页码
     * @param size 每页大小
     * @param tenantName 租户名称
     * @param contactPhone 联系电话
     * @param contactPerson 联系人
     * @param tenantId 租户ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 分页结果
     */
    @GetMapping("/list")
    public Result getTenants(@RequestParam(name = "page", defaultValue = "1") Integer page,
                            @RequestParam(name = "size", defaultValue = "10") Integer size,
                            @RequestParam(name = "tenantName", required = false) String tenantName,
                            @RequestParam(name = "contactPhone", required = false) String contactPhone,
                            @RequestParam(name = "contactPerson", required = false) String contactPerson,
                            @RequestParam(name = "tenantId", required = false) Integer tenantId,
                            @RequestParam(name = "startTime", required = false) String startTime,
                            @RequestParam(name = "endTime", required = false) String endTime) {
        Map<String, Object> result = tenantService.getTenants(page, size, tenantName, contactPhone, contactPerson, tenantId, startTime, endTime);
        return Result.success("获取租户列表成功", result);
    }


    @PostMapping(value = "/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result addTenants(
            @RequestPart(name = "file") MultipartFile file,
            @RequestParam(name = "tenantName") String tenantName,
            @RequestParam(name = "tenantIcon") String tenantIcon,
            @RequestParam(name = "contactPerson") String contactPerson,
            @RequestParam(name = "contactPhone") String contactPhone,
            @RequestParam(name = "adminName") String adminName,
            @RequestParam(name = "remark") String remark
    ) {
        Tenant tenant = new Tenant();
        tenant.setTenantName(tenantName);
        tenant.setTenantIcon(tenantIcon);
        tenant.setContactPerson(contactPerson);
        tenant.setContactPhone(contactPhone);
        tenant.setAdminName(adminName);
        tenant.setRemark(remark);

        Tenant newTenant = tenantService.addTenants(file, tenant);
        return Result.success("新增成功", newTenant);
    }
    
    /**
     * 更新租户信息
     * @param tenantId 租户ID
     * @return 操作结果
     */
    @PutMapping("/{tenantId}")
    public Result updateTenant(
            @PathVariable(name = "tenantId") Integer tenantId,
            @RequestPart(name = "file", required = false) MultipartFile file,
            @RequestPart(name = "data") String dataJson) throws IOException {

        // 解析 JSON 数据
        ObjectMapper objectMapper = new ObjectMapper();
        Tenant tenant = objectMapper.readValue(dataJson, Tenant.class);
        tenant.setTenantId(tenantId);

        tenantService.updateTenant(tenant ,file);
        return Result.success("更新成功");
    }
    
    /**
     * 删除租户
     * @param tenantId 租户ID
     * @return 操作结果
     */
    @DeleteMapping("/{tenantId}")
    public Result deleteTenant(@PathVariable(name = "tenantId") Integer tenantId) {
        tenantService.deleteTenant(tenantId);
        return Result.success("删除成功");
    }

    /**
     * 获取图形验证码
     * @return base64图片和uuid
     */
    @GetMapping("/captcha")
    public Result getCaptcha() {
        CaptchaUtil.Captcha captcha = CaptchaUtil.generateCaptcha(120, 40, 5);
        String uuid = UUID.randomUUID().toString();
        captchaCache.put(uuid, captcha.code);
        Map<String, String> data = new HashMap<>();
        data.put("img", "data:image/png;base64," + captcha.base64Img);
        data.put("uuid", uuid);
        return Result.success("获取验证码成功", data);
    }

    /**
     * 校验验证码
     */
    private boolean checkCaptcha(String uuid, String code) {
        if (uuid == null || code == null) return false;
        String realCode = captchaCache.get(uuid);
        if (realCode != null && realCode.equalsIgnoreCase(code)) {
            captchaCache.remove(uuid); // 用过即删
            return true;
        }
        return false;
    }

    /**
     * 租户注册接口
     */
    @PostMapping(value="/register", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result addTenants(
            @RequestPart(name = "file") MultipartFile file,
            @RequestParam(name = "tenantName") String tenantName,
            @RequestParam(name = "tenantIcon") String tenantIcon,
            @RequestParam(name = "contactPerson") String contactPerson,
            @RequestParam(name = "contactPhone") String contactPhone,
            @RequestParam(name = "adminName") String adminName,
            @RequestParam(name = "password") String password,
            @RequestParam(name = "code") String code,
            @RequestParam(name = "uuid") String uuid) {
        // 校验验证码
        if (!checkCaptcha(uuid, code)) {
            return Result.error("验证码错误或已过期");
        }
        // 新增租户
        Tenant tenant = new Tenant();
        tenant.setTenantName(tenantName);
        tenant.setTenantIcon(tenantIcon);
        tenant.setContactPerson(contactPerson);
        tenant.setContactPhone(contactPhone);
        tenant.setAdminName(adminName);
        tenant.setRegisterTime(new java.util.Date());
        tenantService.addTenants(file, tenant); // 自动创建部门和用户

        // 更新管理员密码（addTenants默认密码为tenantId，这里改为前端传递的密码）
        Department dept = departmentService.getDepartmentByName(tenantName);
        User admin = userService.getUserByName(adminName);
        if (admin != null) {

            admin.setPassword(password);
            admin.setDepartmentId(dept != null ? dept.getDepartmentId() : null);
            admin.setUserType(1);
            admin.setUserStatus(0);
            admin.setGender(1);
            admin.setRegisterTime(new java.util.Date());
            userService.updateUser(admin);
        }
        return Result.success("注册成功", tenant);
    }

    /**
     * 上传租户图片并保存URL到数据库
     * @param tenantId 租户ID
     * @param file 图片文件
     * @return 图片URL
     */
    @PostMapping("/uploadIcon")
    public Result upload(@RequestParam(name = "tenantId") Integer tenantId, @RequestParam(name = "file") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            // 上传文件到OSS
            String url = UploadUtil.uploadImage(file);
            log.info(url);
            // 更新数据库中的tenant_icon字段
            Tenant tenant = new Tenant();
            tenant.setTenantId(tenantId);
            tenant.setTenantIcon(url);
            tenantService.updateTenant(tenant, file);
            return Result.success(url);
        }
        return Result.error("上传失败");
    }

    @PostMapping("/deleteIcon")
    public Result deleteIcon(@RequestParam(name = "url") String url) throws Exception {
        if (url == null || url.isEmpty()) {
            return Result.error("删除失败");
        }
        try {
            tenantService.deleteIcon(url);
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error("删除失败");
        }
    }
}